package com.travel.dao.impl;

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;

import com.travel.core.AbstractDao;
import com.travel.dao.ITourDao;
import com.travel.entities.Spot;

/**
 * @author SAGITTAR
 */
public class TourDaoImpl extends AbstractDao implements ITourDao {

    private static final Logger LOGGER = LogManager.getLogger(TourDaoImpl.class);

    @Override
    public int selectCount() {
        return selectNumberByClassTypeAndSql("SELECT count(1) FROM tour").intValue();
    }

    @Override
    public List<Spot> selectList(String groupBy, String orderBy, Direction direction, int start, int count,
            boolean hasDate) {
        String sql = "SELECT AVG(rating) spotAvgRating, COUNT(1) spotRatingCount, spotId, spotName ";
        StringBuilder sqlBuilder = new StringBuilder(sql);
        sqlBuilder.append("FROM tour ");
        if (hasDate) {
            // 为何时间限制在2017年3月？？
            sqlBuilder.append("WHERE a.date >= DATE('2017-03-01') AND a.date <= DATE('2017-03-31') ");
        }
        sqlBuilder.append("GROUP BY %s ");
        sqlBuilder.append("ORDER BY %s %s ");
        sqlBuilder.append("LIMIT %s, %s");
        String preparedSql = String.format(sqlBuilder.toString(), groupBy, orderBy, direction, start, count);
        List<Spot> spotList = selectListByClassTypeAndSql(Spot.class, preparedSql);
        LOGGER.info(getResultLog(), new JSONArray(spotList));
        return spotList;
    }

    @Override
    public List<Spot> selectList(String groupBy, String orderBy, Direction direction, int start, int count) {
        return selectList(groupBy, orderBy, direction, start, count, false);
    }
}
